package Test;

import exception.BaseException;
import jdk.nashorn.internal.runtime.options.Option;
import vo.Student;

import java.util.List;
import java.util.Optional;

/**
 * https://zhuanlan.zhihu.com/p/40966718 optional总结
 */
public class TestOptional {

    public static void test1() {
        Student student = null;
        Optional<Student> op = Optional.of(student);
        System.out.println(op.orElse(new Student(1, "name", "bb")));
    }

    //查询数据库返回一个对象避免空指针
    public static void test2() {
        Student student = null;
        Student st = Optional.ofNullable(student).orElseGet(() -> new Student());
        System.out.println(st.getName());

    }

    //没有查询到抛异常
    public static void test3() {
        Student student = null;
        Student student1 = Optional.ofNullable(student).orElseThrow(() -> new BaseException("出错"));
        System.out.println(student1.getName());
    }

    //map操作
    public static void test4() {
        Student st = null;
        Optional<String> optionalS = Optional.ofNullable(st)
                .map(e -> e.getName());

        System.out.println(optionalS.orElse("1"));

    }

    //多次map
    public static void test5() {
        Student st = null;
        String s = Optional.ofNullable(new Student())
                .map(e -> e.getName())
                .map(name -> name.toUpperCase())
                .map(name -> name.replace("_", ""))
                .orElse("unKnow");
        System.out.println(s);
    }

    //flatMap
    public static void test6() {
        Integer integer = Optional.ofNullable(new Student())
                .flatMap(e -> Optional.ofNullable(e.getId()))
                .orElse(1);
        System.out.println(integer);
    }

    //filter
    public static void test7() {
        String unKnow = Optional.ofNullable(new Student())
                .filter(e -> e.getId() > 6)
                .map(Student::getName)
                .orElse("unKnow");
        System.out.println(unKnow);
    }

    //模拟两个对象set
    public static void test8() {
        Student target = new Student();

        Student student = new Student(1, "小明", "日本");
        Student student1=null;
        Optional<Student> op = Optional.ofNullable(student1);
        target.setScore(op.orElse(new Student()).getId());
        System.out.println(target);
    }


    public static void main(String[] args) {
        List<Student> list=null;

        Optional.ofNullable(list).ifPresent(list1 ->{
            for (Student student : list1) {
                System.out.println(student.getId());
            }
        });
    }
}
